package com.lance.answer.gui.answer.gk.answer.lms.util;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.util.image_valid.ValidUtils;
import net.sourceforge.tess4j.TesseractException;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

public class LmsUtil {


    public static final String ValidLock = "ValidLock";



    public static List<String> getVip() {
        List<String> vip = Lists.newArrayList(

                "2112001251021"

        );


        return vip;

    }

    public static Map<Long, String> getUserCourseMap(String userCode) {
        Map<Long, String> courseMap = null;
        try {
            File file = new File("libs//lmsCourseInfo//" + userCode + ".json");
            if(!file.exists()){
                return null;
            }
            InputStream inputStream = new FileInputStream(file);
            String courseInfoStr = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
            Map<Object, Object> origin = JSONObject.parseObject(courseInfoStr, Map.class);
            courseMap = Maps.newHashMap();
            for (Map.Entry<Object, Object> entry : origin.entrySet()) {
                courseMap.put(Long.parseLong(String.valueOf(entry.getKey())), String.valueOf(entry.getValue()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return courseMap;
    }

    public static Map<Long, String> getUserCourseMap(String userCode,String teacher) {
        Map<Long, String> courseMap = null;
        try {
            File file = new File("libs//lmsCourseInfo//" +teacher+"//"+ userCode + ".json");
            if(!file.exists()){
                return null;
            }
            InputStream inputStream = new FileInputStream(file);
            String courseInfoStr = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
            Map<Object, Object> origin = JSONObject.parseObject(courseInfoStr, Map.class);
            courseMap = Maps.newHashMap();
            for (Map.Entry<Object, Object> entry : origin.entrySet()) {
                courseMap.put(Long.parseLong(String.valueOf(entry.getKey())), String.valueOf(entry.getValue()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return courseMap;
    }

    public static Map<Long, String> getUserCourseInfo(WebDriver driver) throws InterruptedException {
        Map<Long, String> courseMap = Maps.newHashMap();
        List<String> courseNames = Lists.newArrayList();
        for (WebElement we : driver.findElements(By.cssSelector("div[class='ouchnPc_index_course_div']"))) {
            String textContent = we.getText();
            System.err.println("text:" + textContent);
            System.err.println("title:" + we.findElement(By.tagName("p")).getText());
            courseNames.add(we.findElement(By.tagName("p")).getText());
        }

        for (String courseName : courseNames) {
            Util.switchToFirst(driver);
            driver.navigate().refresh();
            Thread.sleep(5000);
            for (WebElement we : driver.findElements(By.cssSelector("div[class='ouchnPc_index_course_div']"))) {
                if (courseName.contains(we.findElement(By.tagName("p")).getText())) {
                    we.findElement(By.tagName("a")).click();
                    Thread.sleep(1000);
                    Util.switchToLast(driver);
                    Thread.sleep(8000);
                    String cUrl = driver.getCurrentUrl();
                    String cid = cUrl.substring(cUrl.indexOf("/course/") + 8, cUrl.indexOf("/ng#"));
                    courseMap.put(Long.parseLong(cid), courseName);
                    driver.close();
                    Thread.sleep(2000);
                    break;
                }
            }

        }
        return courseMap;
    }



    public static  void login(WebDriver driver, String userName, String pwd) {

        // 循环获取
        boolean loop1 = true;
        boolean refresh = false;
        while (loop1) {
            if(refresh){
                String url = "https://menhu.pt.ouchn.cn/site/ouchnPc/index";
                driver.get(url);
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            WebElement userNameInput = driver.findElement(By.id("loginName"));
            userNameInput.clear();
            userNameInput.sendKeys(userName);

            WebElement passwordInput = driver.findElement(By.id("password"));
            passwordInput.clear();
            passwordInput.sendKeys(pwd);

            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // FIXME 还得刷新验证码！！！！！！！！！！！！！！！

            WebElement element = driver.findElement(By.id("kaptchaImage"));

            File image = element.getScreenshotAs(OutputType.FILE);

            //element.click();

            String validateCode = "";
            try {

                validateCode = ValidUtils.valid(image);

                Thread.sleep(3000);

                System.out.println("verifyCode: " + validateCode);
                WebElement validateCodeInput = driver.findElement(By.id("validateCode"));
                validateCodeInput.clear();
                if(Strings.isNullOrEmpty(validateCode)){

                    String url = "https://menhu.pt.ouchn.cn/site/ouchnPc/index";
                    driver.get(url);
                    Thread.sleep(6000);
                   continue;
                }
                validateCodeInput.sendKeys(validateCode);
                Thread.sleep(3000);
                Thread.sleep(1000);
                WebElement loginBtn = driver.findElement(By.name("button"));
                loginBtn.click();
                Thread.sleep(2000);
            } catch (Exception e) {
                loop1 = true;
                refresh = true;
                // e.printStackTrace();
            }


           // if (driver.getCurrentUrl().contains("index")) {
            if (driver.getCurrentUrl().equals("https://menhu.pt.ouchn.cn/site/ouchnPc/index")) {
                loop1 = false;
                refresh = true;
            }
        }

    }

    public static void loginbk(WebDriver driver, String userName, String pwd) {

        // 循环获取
        boolean loop1 = true;
        while (loop1) {

            WebElement userNameInput = driver.findElement(By.id("loginName"));
            userNameInput.clear();
            userNameInput.sendKeys(userName);

            WebElement passwordInput = driver.findElement(By.id("password"));
            passwordInput.clear();
            passwordInput.sendKeys(pwd);

            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // FIXME 还得刷新验证码！！！！！！！！！！！！！！！

            WebElement element = driver.findElement(By.id("kaptchaImage"));

            element.click();

            String validateCode = "";
            try {
                File file = new File("D:\\test\\test2.jpeg");
                if (file.exists()) {
                    file.renameTo(new File("D:\\test\\test444.jpeg"));
                }

                // http://t.zoukankan.com/lclq-p-6514427.html
                // 1、右键点击图片；
                new Actions(driver).contextClick(element).perform();
                Robot robot = new Robot();
                robot.keyPress(KeyEvent.VK_DOWN);
                Thread.sleep(1000);
                robot.keyPress(KeyEvent.VK_DOWN);
                Thread.sleep(1000);

                robot.keyRelease(KeyEvent.VK_DOWN);
                Thread.sleep(1000);
                robot.keyPress(KeyEvent.VK_ENTER);
                // D:\test\test2.jpeg
                file = new File("D:\\test\\test2.jpeg");
                if (file.exists()) {
                    file.renameTo(new File("D:\\test\\555.jpeg"));
                }

                Runtime.getRuntime().exec("D:\\software\\autoit\\1.exe");
                Thread.sleep(5000);
                validateCode = ValidUtils.read("D:\\test\\test2.jpeg");
                System.err.println("validateCode:" + validateCode);

                if (Strings.isNullOrEmpty(validateCode)) {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    continue;
                }
                WebElement validateCodeInput = driver.findElement(By.id("validateCode"));
                validateCodeInput.clear();
                validateCodeInput.sendKeys(validateCode);
                Thread.sleep(1000);
                WebElement loginBtn = driver.findElement(By.name("button"));
                loginBtn.click();
                Thread.sleep(2000);
            } catch (Exception e) {
                e.printStackTrace();
            }


            if (driver.getCurrentUrl().contains("index")) {
                loop1 = false;
            }
        }

    }
}
